package com.it.you.common.utils;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池实用工具
 * @since 2022/08/16
 * @version 1.0.8
 */
@Slf4j
public abstract class ExecutorUtil {

    /**
     * 最大线程数
     */
    private static final int MAX_THREAD_NUM = 20;

    /**
     * 全局线程池
     */
    private static ExecutorService EXECUTOR;

    /**
     * 单例模式创建线程池
     * @return
     */
    private static ExecutorService getExecutor() {
        if (EXECUTOR == null) {
            synchronized(ExecutorUtil.class) {
                if (EXECUTOR == null) {
                    EXECUTOR = Executors.newFixedThreadPool(MAX_THREAD_NUM);
                }
            }
        }
        return EXECUTOR;
    }

    /**
     * 执行线程
     * @param runnable
     */
    public static void execute(Runnable runnable) {
        log.info("子线程开始执行");
        getExecutor().execute(runnable);
        state();
    }

    /**
     * 打印线程池状态信息
     */
    public static void state() {
        ThreadPoolExecutor executor = (ThreadPoolExecutor) getExecutor();
        log.info("pool size = {}, active threads = {}, queued tasks = {}, completed tasks = {}", executor.getPoolSize(), executor.getActiveCount(), executor.getQueue().size(), executor.getCompletedTaskCount());
    }

}
